package com.campus.realm;

import com.campus.token.JwtToken;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.authc.SimpleAuthenticationInfo;

import com.campus.common.JwtUtil;

public class JwtRealm implements Realm {

    @Override
    public String getName() {
        return "JwtRealm";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;  // 自定义的 JwtToken 类型
    }

    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwtToken = (String) token.getPrincipal();  // 获取传入的 JWT Token

        // 验证 JWT Token
        Claims claims = JwtUtil.validateToken(jwtToken);
        if (claims == null) {
            throw new AuthenticationException("Invalid token");
        }

        String username = claims.getSubject();
        // 如果验证通过，返回 SimpleAuthenticationInfo，认证成功
        return new SimpleAuthenticationInfo(username, jwtToken, getName());
    }
}
